# src/config/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from backend.config.settings import settings

# 使用设置中的数据库URL
SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, 
    pool_pre_ping=True,
    pool_recycle=3600,
    pool_size=10,
    max_overflow=20,
    connect_args={
        "connect_timeout": 60,
        "read_timeout": 60,
        "write_timeout": 60
    }
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    """FastAPI 依赖注入用数据库会话生成器

    使用示例：
    def api_endpoint(db: Session = Depends(get_db)):
        # 操作数据库
        pass
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_db_session() -> Session:
    """普通Python代码使用的会话获取方法

    使用示例：
    db = get_db_session()
    # 操作数据库
    db.close()
    """
    return SessionLocal()
